﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ChineseSchool.BLL;
using ChineseSchool.Models.Hethong;
using System.Data;
using System.Net;

namespace ChineseSchool.Admin
{
    public partial class QL_User : System.Web.UI.Page
    {
        private int UserTypeID;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["key"]))
                {
                    if (Request.QueryString["key"].Length > 0)
                    {
                        string UserTypeName = Request.QueryString["key"];
                        M_UserType M_UserType = new B_UserType().Selectby_Type(UserTypeName);
                        if (UserTypeName == "QTV")
                        {
                            lblUserTitle.Text = "quản trị viên";
                        }
                        else if (UserTypeName == "HV")
                        {
                            lblUserTitle.Text = "học viên";
                            pnlIsTop.Visible = true;
                        }
                        else if (UserTypeName == "GV")
                        {
                            lblUserTitle.Text = "giáo viên";
                        }
                        else
                        {
                            lblUserTitle.Text = "người dùng";
                        }
                        UserTypeID = M_UserType.UserTypeID;
                        BinGrid(UserTypeID);
                        btnAdd.Visible = true;
                        btnEdit.Visible = true;
                    }
                }
            }
        }

        protected void BinGrid(int UserTypeID)
        {
            B_User B_User = new B_User();
            List<M_User> lstM_User = B_User.GetBy_UserTypeID(UserTypeID);
            grvUser.DataSource = lstM_User;
            grvUser.DataBind();
        }

        protected void grvUser_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvUser.PageIndex = e.NewPageIndex;
            LayGiatriBien();
            BinGrid(UserTypeID);
        }

        protected void grvUser_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            LayGiatriBien();
            int UserID = Convert.ToInt32(e.CommandArgument);
            M_User M_User = new M_User();
            B_User B_User = new B_User();
            B_Insert_Update_Delete bll = new B_Insert_Update_Delete();
            if (e.CommandName.Equals("Delete", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    bll.delete("Users", "UserID", M_User, UserID);
                    Response.Write("<script>alert('Đã được xóa!')</script>");
                }
                catch (System.Exception ex)
                {
                    throw new Exception("Đã có lỗi xảy ra! Vui lòng thử lại lần sau!", ex);
                }
                BinGrid(UserTypeID);
            }
            if (e.CommandName.Equals("Edit", StringComparison.OrdinalIgnoreCase))
            {
                panAdd.Visible = true;
                btnAdd.Visible = false;
                btnEdit.Visible = true;
                lblTitle.Text = "Cập nhật";
                M_User = B_User.Selectby_id(UserID);
                UserTypeID = Convert.ToInt32(M_User.UserTypeID.ToString());
                if (M_User.IsLock.ToString() == "True")
                {
                    rbYes.Checked = true;
                }
                else
                {
                    rbNo.Checked = true;
                }
                txtUserName.Text = M_User.UserName;
                txtFullName.Text = M_User.FullName.ToString();
                txtEmail.Text = M_User.Email;
                txtAddress.Text = M_User.Address.ToString();
                txtPhoneNumber.Text = M_User.PhoneNumber;

                if (!string.IsNullOrEmpty(M_User.Avatar))
                    imgAvatar.ImageUrl = "/FilesUpload/" + M_User.Avatar;
                else
                    imgAvatar.ImageUrl = "/images/noavatar.png";

                btnEdit.CommandArgument = UserID.ToString();
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            panAdd.Visible = true;
            btnAdd.Visible = true;
            btnEdit.Visible = false;
            lblTitle.Text = "Thêm mới";
            txtUserName.Text = "";
            txtFullName.Text = "";
            txtEmail.Text = "";
            txtPhoneNumber.Text = "";
            txtAddress.Text = "";
            rbYes.Checked = true;
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            LayGiatriBien();
            panAdd.Visible = false;
            btnEdit.Visible = true;
            var mUser = new M_User();
            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                Response.Write("<script type='text/javascript'>alert('Vui lòng nhập tên người dùng!')</script>");
                return;
            }
            mUser.UserName = Server.HtmlEncode(txtUserName.Text);
            mUser.FullName = txtFullName.Text;
            mUser.Email = WebUtility.HtmlEncode(txtEmail.Text);
            mUser.PhoneNumber = WebUtility.HtmlEncode(txtPhoneNumber.Text);
            mUser.Address = txtAddress.Text;
            mUser.IsLock = rbYes.Checked;
            mUser.UserTypeID = UserTypeID;
            mUser.Description = "";
            mUser.JoinDate = DateTime.Now;
            mUser.Password = "123";
            if (pnlIsTop.Visible == true)
            {
                if (rdbIsTop.Checked == true)
                {
                    mUser.IsTop = true;
                }
                else if (rdbNotTop.Checked == true)
                {
                    mUser.IsTop = false;
                }
            }

            if (!string.IsNullOrEmpty(imgAvatar.ImageUrl))
            {
                var getAvatarUrl = imgAvatar.ImageUrl.Split('/');
                var fileName = getAvatarUrl[getAvatarUrl.Length - 1];
                mUser.Avatar = fileName;
            }

            B_Insert_Update_Delete bll = new B_Insert_Update_Delete();
            bll.insert("Users", "UserID", mUser);
            BinGrid(UserTypeID);
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            LayGiatriBien();
            panAdd.Visible = false;
            btnEdit.Visible = true;
            var mUser = new M_User();
            mUser.UserID = Convert.ToInt32(btnEdit.CommandArgument);
            var userId = Convert.ToInt32(btnEdit.CommandArgument);
            mUser = (new B_User()).Selectby_id(userId);
            mUser.UserName = WebUtility.HtmlEncode(txtUserName.Text);
            mUser.FullName = txtFullName.Text;
            mUser.Email = WebUtility.HtmlEncode(txtEmail.Text);
            mUser.PhoneNumber = WebUtility.HtmlEncode(txtPhoneNumber.Text);
            mUser.IsLock = rbYes.Checked;
            mUser.UserTypeID = UserTypeID;
            mUser.Address = txtAddress.Text;
            B_Insert_Update_Delete bll = new B_Insert_Update_Delete();
            bll.update("Users", "UserID", mUser, userId);
            BinGrid(UserTypeID);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            LayGiatriBien();
            panAdd.Visible = false;
            btnAdd.Visible = true;
            btnEdit.Visible = true;
            txtUserName.Text = "";
            txtFullName.Text = "";
            txtEmail.Text = "";
            txtPhoneNumber.Text = "";
            txtAddress.Text = "";
            rbYes.Checked = true;
            BinGrid(UserTypeID);
        }

        protected void grvUser_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            LayGiatriBien();
            BinGrid(UserTypeID);
        }

        protected void grvUser_RowEditing(object sender, GridViewEditEventArgs e)
        {
            LayGiatriBien();
            grvUser.EditIndex = e.NewEditIndex;
            BinGrid(UserTypeID);
        }

        protected void LayGiatriBien()
        {
            if (Request.QueryString["key"].ToString() != null && Request.QueryString["key"].ToString() != "")
            {
                string UserTypeName = Request.QueryString["key"].ToString();
                M_UserType M_UserType = new B_UserType().Selectby_Type(UserTypeName);
                UserTypeID = M_UserType.UserTypeID;
                if (UserTypeName == "QTV")
                {
                    lblUserTitle.Text = "quản trị viên";
                }
                else if (UserTypeName == "HV")
                {
                    lblUserTitle.Text = "học viên";
                }
                else if (UserTypeName == "GV")
                {
                    lblUserTitle.Text = "giáo viên";
                }
                else
                {
                    lblUserTitle.Text = "người dùng";
                }
            }
        }

        protected void BtnSelectImageClick(object sender, EventArgs e)
        {
            if (uploadAvatar.HasFile)
            {
                var fileName = txtUserName.Text + DateTime.Now.ToString("yyyyMMddHHssfff") + "_" + uploadAvatar.FileName;
                var filePath = Server.MapPath("/FilesUpload/" + fileName);
                uploadAvatar.SaveAs(filePath);
                imgAvatar.ImageUrl = "/FilesUpload/" + fileName;
            }
        }
    }

}